<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <el-dialog
    v-model="dialogVisible"
    :title="modelValue.id ? '编辑供应商' : '新增供应商'"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
      <el-form-item label="供应商名称" prop="supplierName">
        <el-input
          v-model="formData.supplierName"
          placeholder="请输入供应商名称"
          maxlength="50"
        />
      </el-form-item>

      <el-form-item label="联系电话" prop="phone">
        <el-input
          v-model="formData.phone"
          placeholder="请输入联系电话"
          maxlength="20"
        />
      </el-form-item>

      <el-form-item label="联系地址" prop="address">
        <el-input
          v-model="formData.address"
          placeholder="请输入联系地址"
          type="textarea"
          rows="3"
          maxlength="200"
        />
      </el-form-item>

      <el-form-item label="供应商状态" prop="status">
        <el-select
          v-model="formData.status"
          placeholder="请选择供应商状态"
        >
          <el-option label="正常合作" value="1" />
          <el-option label="合作终止" value="0" />
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确认</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch } from 'vue';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  modelValue: {
    type: Object,
    default: () => ({})
  }
});

const emit = defineEmits(['update:visible', 'save', 'close']);

// 本地响应式变量，避免直接修改prop
const dialogVisible = ref(props.visible);

// 监听prop变化，同步到本地变量
watch(
  () => props.visible,
  (newVal) => {
    dialogVisible.value = newVal;
  }
);

// 监听本地变量变化，同步到父组件
watch(
  () => dialogVisible.value,
  (newVal) => {
    emit('update:visible', newVal);
  }
);

const formRef = ref(null);
const formData = reactive({
  id: '',
  supplierName: '',
  phone: '',
  address: '',
  status: '1' // 默认正常合作，使用字符串值匹配选择器
});

// 表单验证规则
const formRules = reactive({
  supplierName: [
    { required: true, message: '请输入供应商名称', trigger: 'blur' },
    { min: 2, max: 50, message: '名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$|^0\d{2,3}-\d{7,8}$/, message: '请输入正确的电话号码格式', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择供应商状态', trigger: 'change' }
  ]
});

// 监听modelValue变化，实现数据回显
watch(
  () => props.modelValue,
  (newVal) => {
    if (newVal && newVal.id) {
      // 编辑状态 - 复制数据，并确保状态值为字符串
      formData.id = newVal.id;
      formData.supplierName = newVal.supplierName || '';
      formData.phone = newVal.phone || '';
      formData.address = newVal.address || '';
      // 将数字状态转换为字符串，确保与选择器选项匹配
      formData.status = newVal.status !== undefined ? String(newVal.status) : '1';
    } else {
      // 新增状态 - 重置表单
      Object.keys(formData).forEach(key => {
        // 状态字段默认为"1"（正常合作），其他字段设为空字符串
        formData[key] = key === 'status' ? '1' : '';
      });
    }
  },
  { immediate: true }
);

// 监听dialogVisible变化，重置表单验证状态
watch(
  () => dialogVisible.value,
  (newVal) => {
    if (!newVal && formRef.value) {
      formRef.value.clearValidate();
    }
  }
);

const handleSubmit = async () => {
  try {
    // 表单验证
    await formRef.value.validate();

    // 转换状态为数字类型
    const submitData = {
      ...formData,
      status: Number(formData.status) // 提交时转换为数字
    };

    // 提交数据
    emit('save', submitData);
  } catch (error) {
    console.log('表单验证失败:', error);
  }
};

const handleClose = () => {
  dialogVisible.value = false;
  emit('close');
};
</script>

<style scoped>
.supplier-form {
  margin-top: 15px;
}

::v-deep .el-form-item {
  margin-bottom: 15px;
}
</style>
